﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class home_Catalog : System.Web.UI.Page
{
    int page_current = 1;
    public int projectId=0;
    public bool projectIsPublic = false;
    public int currentPermission = 3;// permission in this project

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["id_user"] == null || Session["permission"] == null || ((int)Session["permission"])<=1)
            Response.Redirect("../login.aspx");

        #region get projectId and get it's public property
        if (Request.QueryString["project"] != null)
        {
            try
            {
                projectId = Int32.Parse(Request.QueryString["project"]);
                // checking current project is exist
                string sql = "SELECT id,[public] FROM project WHERE id=" + comm.to_sql(projectId.ToString(), "number");
                DataTable dtTable = dal.SelectTable(sql);
                if (dtTable.Rows.Count != 1)
                    throw new Exception();
                string strPublic = dtTable.Rows[0]["public"].ToString();
                if (strPublic.ToLower() == "true")
                    projectIsPublic = true;
            }
            catch
            {
                projectId = 0;
            }
        }
        #endregion

        #region check current user is enable to access this project
        if (projectId > 0)
        {
            SqlParameter[] listParams = new SqlParameter[3];
            //-- param 1: @userId
            int userId = Int32.Parse(Session["id_user"].ToString());
            SqlParameter param = new SqlParameter("@userId", userId);
            param.SqlDbType = SqlDbType.Int;
            param.Direction = ParameterDirection.Input;
            listParams[0] = param;

            //-- param 2: @projectId
            param = new SqlParameter("@projectId", projectId);
            param.SqlDbType = SqlDbType.Int;
            param.Direction = ParameterDirection.Input;
            listParams[1] = param;

            //-- param 3: @isAccess
            param = new SqlParameter();
            param.ParameterName = "@isAccess";
            param.SqlDbType = SqlDbType.Int;
            param.Direction = ParameterDirection.Output;
            listParams[2] = param;

            dal.ExecuteSP("proCheckAccessProject_GET", listParams);
            int enable = Int32.Parse(listParams[2].Value.ToString());
            if (enable == 0)
                return;
        }
        #endregion

        #region get currentPermission of current user in this project
        if (projectId > 0)
        {
            if (((int)Session["permission"]) >= 4)
            {
                string sql = " SELECT permission FROM UserProject " +
                      " WHERE userId=" + comm.to_sql(Session["id_user"].ToString(), "number") +
                      " AND projectId=" + comm.to_sql(projectId.ToString(), "number");
                DataTable dtTable = dal.SelectTable(sql);
                if (dtTable.Rows.Count == 1)
                {
                    currentPermission = Int32.Parse(dtTable.Rows[0]["permission"].ToString());
                }
            }
        }
        #endregion

        #region check type of user and permission in this project
        if (((int)Session["permission"]) >= 5) // current user is user
        {
            if (projectId == 0)
            {
                Response.Redirect("../home/default.aspx");
                return;
            }
            else if (!projectIsPublic)
            {
                Response.Redirect("../home/work.aspx?project=" + projectId.ToString() + "&user=" + Session["id_user"].ToString());
                return;
            }
            else
            {
                add.Visible = false;
            }
        }
        if (((int)Session["permission"]) == 4) // current user is leader
        {
            if (projectId == 0)
            {
                Response.Redirect("../home/default.aspx");
                return;
            }
            else
            {
                if (currentPermission >= 5)
                {
                    if (!projectIsPublic)
                    {
                        Response.Redirect("../home/work.aspx?project=" + projectId.ToString() + "&user=" + Session["id_user"].ToString());
                        return;
                    }
                    else
                    {
                        add.Visible = false;
                    }
                }
            }
        }

        #endregion
        
        #region get current page
        if (Request.QueryString["page"] != null)
        {
            try
            {
                page_current = Int32.Parse(Request.QueryString["page"]);
            }
            catch
            {
                page_current = 1;
            }
        }
        #endregion
        
        if (!IsPostBack)
        {
            #region bind data
            string strOrderby = orderby.SelectedValue;
            if (Session["orderby_cat"] != null)
            {
                strOrderby = Session["orderby_cat"].ToString();
                orderby.Items.FindByValue(orderby.SelectedValue).Selected = false;
                orderby.Items.FindByValue(strOrderby).Selected = true;
            }
            string strOrder = order.SelectedValue;
            if (Session["order_cat"] != null)
            {
                strOrder = Session["order_cat"].ToString();
                order.Items.FindByValue(order.SelectedValue).Selected = false;
                order.Items.FindByValue(strOrder).Selected = true;
            }
            BindData(strOrderby, strOrder);
            BindData1();
            #endregion
        }
    }

    private void BindData(string orderby,string order)
    {
        //display.Text = orderby + " " + order;
        int page_number = 0;

        // load list of catalogs
        if (Session["id_user"] != null && Session["permission"] != null)
        {
            SqlParameter[] listParams = new SqlParameter[7];
            //-- param 1: @id_user
            int id = Int32.Parse(Session["id_user"].ToString());
            SqlParameter param = new SqlParameter("@id_user", id);
            param.SqlDbType = SqlDbType.Int;
            param.Direction = ParameterDirection.Input;
            listParams[0] = param;

            //-- param 2: @page_size
            param = new SqlParameter("@page_size", 10);
            param.SqlDbType = SqlDbType.Int;
            param.Direction = ParameterDirection.Input;
            listParams[1] = param;

            //-- param 3: @page_current
            param = new SqlParameter("@page_current", page_current);
            param.SqlDbType = SqlDbType.Int;
            param.Direction = ParameterDirection.Input;
            listParams[2] = param;

            // -- param 4: @orderby
            param = new SqlParameter("@orderby", orderby);
            param.SqlDbType = SqlDbType.VarChar;
            param.Size = 50;
            param.Direction = ParameterDirection.Input;
            listParams[3] = param;

            // -- param 5: @typeorder
            param = new SqlParameter("@typeorder", order);
            param.SqlDbType = SqlDbType.VarChar;
            param.Size = 50;
            param.Direction = ParameterDirection.Input;
            listParams[4] = param;

            // -- param 6: @projectId
            param = new SqlParameter("@projectId", projectId);
            param.SqlDbType = SqlDbType.Int;
            param.Direction = ParameterDirection.Input;
            listParams[5] = param;

            //-- param 7: @page_number
            param = new SqlParameter();
            param.ParameterName = "@page_number";
            param.SqlDbType = SqlDbType.Int;
            param.Direction = ParameterDirection.Output;
            listParams[6] = param;

            DataTable dtTable = dal.SelectTableSP("proCatalog_SEL", listParams);
            page_number = Int32.Parse(listParams[6].Value.ToString());

            // display full info of catalogs in gridview

            catalogs.DataSource = dtTable;
            catalogs.DataBind();
            int permisssion = (int)Session["permission"];
            if (projectId == 0)    // Load all catalogs of all projects
            {
                viewAll.Visible = false;
            }
            else // load all catalogs of a project
            {
                if (permisssion != 2 && permisssion != 3)
                {
                    if(currentPermission>=5)
                        catalogs.Columns[7].Visible = false;
                }
                viewAll.NavigateUrl = "../home/work.aspx?project="+projectId.ToString();
                viewAll.Visible = true;
            }
        }

        // display pager
        if (page_number == 0)
        {
            display.Text = "Chưa có chuyên mục nào !";
            pager.Visible = false;
            this.order.Visible = false;
            this.orderby.Visible = false;
            this.label1.Visible = false;
            this.label2.Visible = false;
            viewAll.Visible = false;

            // check if there isn't any project -> hide menu
            if (Session["projectnumber"] != null)
            {
                int number = Int32.Parse(Session["projectnumber"].ToString());
                if (number == 0)
                {
                    menu.Enabled = false;
                    menu.Visible = false;
                }
            }

            // check current user can or can't access to current project
            // if not, hide menu
            if (projectId != 0)
            {
                SqlParameter[] listParams = new SqlParameter[3];
                //-- param 1: @userId
                int id = Int32.Parse(Session["id_user"].ToString());
                SqlParameter param = new SqlParameter("@userId", id);
                param.SqlDbType = SqlDbType.Int;
                param.Direction = ParameterDirection.Input;
                listParams[0] = param;

                //-- param 2: @projectId
                param = new SqlParameter("@projectId", projectId);
                param.SqlDbType = SqlDbType.Int;
                param.Direction = ParameterDirection.Input;
                listParams[1] = param;

                //-- param 3: @isAccess
                param = new SqlParameter();
                param.ParameterName = "@isAccess";
                param.SqlDbType = SqlDbType.Int;
                param.Direction = ParameterDirection.Output;
                listParams[2] = param;

                dal.ExecuteSP("proCheckAccessProject_GET", listParams);
                int enable = Int32.Parse(listParams[2].Value.ToString());
                if (enable == 0)
                {
                    menu.Enabled = false;
                    menu.Visible = false;
                }
            }
        }
        else if (page_number == 1)
        {
            pager.Visible = false;
            display.Text = "";
        }
        else if (page_number > 1)
        {
            display.Text = "";
            // load pager
            pager.link = "~/home/catalog.aspx";
            pager.numberpage = page_number;
            pager.currentpage = page_current;
            pager.paramPageName = "page";
            pager.Visible = true;
            pager.BindData();
        }
    }

    private void BindData1()
    {
        // load list priority
        priority_catalog.Attributes["style"] = "margin:0;";
        ListItem liItem = new ListItem(DisplayEnum.DisplayPriority((int)Priority.normal), ((int)Priority.normal).ToString());
        liItem.Selected = true;
        priority_catalog.Items.Add(liItem);

        liItem = new ListItem(DisplayEnum.DisplayPriority((int)Priority.priority), ((int)Priority.priority).ToString());
        priority_catalog.Items.Add(liItem);

        liItem = new ListItem(DisplayEnum.DisplayPriority((int)Priority.hurry), ((int)Priority.hurry).ToString());
        priority_catalog.Items.Add(liItem);

        liItem = new ListItem(DisplayEnum.DisplayPriority((int)Priority.urgent), ((int)Priority.urgent).ToString());
        priority_catalog.Items.Add(liItem);

        // load list project for adding catalog
        project_catalog.Attributes["style"] = "margin:0;";
        if (((int)Session["permission"]) == 4 && projectId !=0)   // user is leader
        {
            // get id and name of current project
            string sql = "SELECT id,name FROM project,UserProject " +
                        "WHERE id=" + comm.to_sql(projectId.ToString(), "number") +
                        " AND project.id=UserProject.projectId " +
                        " AND UserProject.userId =" + comm.to_sql(Session["id_user"].ToString(),"number");
            DataTable dtTable = dal.SelectTable(sql);
            if (dtTable.Rows.Count == 1)
            {
                ListItem item = new ListItem(dtTable.Rows[0]["name"].ToString(), dtTable.Rows[0]["id"].ToString());
                project_catalog.Items.Add(item);
            }
        }
        else if (((int)Session["permission"]) == 2 || ((int)Session["permission"]) == 3) // user is register or manager
        {
            // get list names of projects
            int id = Int32.Parse(Session["id_user"].ToString());
            SqlParameter param = new SqlParameter("@id_user", id);
            param.SqlDbType = SqlDbType.Int;
            param.Direction = ParameterDirection.Input;
            DataTable dtTable = dal.SelectTableSP("proUser_ProjectName_SEL", param);

            // display names of projects in dropdownlist
            foreach (DataRow row in dtTable.Rows)
            {
                ListItem item = new ListItem(row["name"].ToString(), row["id"].ToString());
                project_catalog.Items.Add(item);
            }

            // set current project is selected
            if (projectId != 0)
            {
                if (project_catalog.Items.FindByValue(projectId.ToString()) != null)
                {
                    project_catalog.Items.FindByValue(projectId.ToString()).Selected = true;
                }
            }

        }
    }

    protected void orderby_SelectedIndexChanged(object sender, EventArgs e)
    {
        string strOrderby = ((DropDownList)sender).SelectedValue;
        Session.Add("orderby_cat", strOrderby);
        Session.Timeout = 60;
        string strOrder = order.SelectedValue;
        BindData(strOrderby, strOrder);
    }

    protected void order_SelectedIndexChanged(object sender, EventArgs e)
    {
        string strOrder = ((DropDownList)sender).SelectedValue;
        Session.Add("order_cat", strOrder);
        Session.Timeout = 60;
        string strOrderby = orderby.SelectedValue;
        BindData(strOrderby, strOrder);
    }

    protected void btOk_Click(object sender, EventArgs e)
    {
        string strOrderby = (Session["orderby_cat"] != null ? Session["orderby_cat"].ToString() : orderby.SelectedValue);
        string strOrder = (Session["order_cat"] != null ? Session["order_cat"].ToString() : order.SelectedValue);
        BindData(strOrderby, strOrder);
    }

    protected void catalogs_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "removeCatalog")
        {
            //string sql = "DELETE FROM [catalog] WHERE id=" + comm.to_sql(e.CommandArgument.ToString(), "number");
            //dal.Execute(sql);
            string strOrderby = (Session["orderby_cat"] != null ? Session["orderby_cat"].ToString() : orderby.SelectedValue);
            string strOrder = (Session["order_cat"] != null ? Session["order_cat"].ToString() : order.SelectedValue);
            BindData(strOrderby, strOrder);
        }
    }
}
